package org.example.school.service.impl;

import org.example.school.entity.Parents;
import org.example.school.entity.Students;
import org.example.school.entity.Teachers;
import org.example.school.entity.Users;
import org.example.school.mapper.ParentsMapper;
import org.example.school.mapper.StudentsMapper;
import org.example.school.mapper.TeachersMapper;
import org.example.school.mapper.UsersMapper;
import org.example.school.model.dto.UserDTO;
import org.example.school.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-09-28
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {
    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private StudentsMapper studentsMapper;
    @Autowired
    private TeachersMapper teachersMapper;
    @Autowired
    private ParentsMapper parentsMapper;

    @Override
    public Users login(String username, String password) {
        Users user = this.findByUsername(username);
        if (user != null && passwordEncoder.matches(password, user.getPasswordHash())){
            return user;
        }
        return null;
    }
    @Transactional
    @Override
    public boolean register(UserDTO userDTO) {
        // 1. 检查用户名是否已存在
        if (findByUsername(userDTO.getUsername()) != null) {
            // 在实际项目中，最好抛出自定义异常
            return false;
        }

        // 2. 创建并保存通用Users对象
        String encodedPassword = passwordEncoder.encode(userDTO.getPassword());
        Users newUser = new Users(userDTO.getUsername(), encodedPassword, userDTO.getUserType());
        this.save(newUser); // 保存后，newUser对象会获得数据库生成的ID

        // 3. 根据用户类型，在对应的表中创建记录
        String userType = userDTO.getUserType();
        if ("1".equals(userType)) { // 老师
            if (!StringUtils.hasText(userDTO.getTeacherNumber())) {
                throw new IllegalArgumentException("教师注册必须提供教师编号");
            }
            Teachers teacher = new Teachers();
            teacher.setUserId(newUser.getId());
            teacher.setFullName(userDTO.getFullName());
            teachersMapper.insert(teacher);
        } else if ("2".equals(userType)) { // 学生
            // 检查学号是否提供
            if (!StringUtils.hasText(userDTO.getStudentNumber())) {
                throw new IllegalArgumentException("学生注册必须提供学号");
            }
            Students student = new Students();
            student.setUserId(newUser.getId());
            student.setFullName(userDTO.getFullName());
            student.setStudentNumber(userDTO.getStudentNumber());
            // 其他信息如班级ID等，可以后续由管理员分配
            // 这里为了能插入成功，需要给class_id一个数据库中存在的值，或者将其设置为可空
            // 假定为1L，实际应有分配逻辑
            student.setClassId(1);
            studentsMapper.insert(student);
        } else if ("3".equals(userType)) { // 监护人
            Parents parent = new Parents();
            parent.setUserId(newUser.getId());
            parent.setFullName(userDTO.getFullName());
            parentsMapper.insert(parent);
        } else {
            throw new IllegalArgumentException("无效的用户类型");
        }
        return true;
    }



    @Override
    public boolean save(Users user) {
        return usersMapper.insert(user) > 0;
    }
    @Override
    public Users findByUsername(String username) {
        return this.lambdaQuery().eq(Users::getUsername, username).one();
    }

}
